package com.itheima.day16.第三题;

import java.io.*;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

//请使用ConcurrentHashMap定义一个线程安全的Map，使用两个线程访问它：
//
//​       第一个线程：向集合中添加键、值都是：1--10000的数字；
//
//​       第二个线程：向集合中添加键、值都是：10001--20000的数字；
//
//​       确保两个线程全部操作集合完毕，然后打印集合的每个元素，测试期准确性
public class demo3 {
    public static void main(String[] args) throws InterruptedException {
        int count = 0;
        ConcurrentHashMap<Integer,Integer> concurrentHashMap = new ConcurrentHashMap<>();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(()->{
            for (int i = 1; i <= 10000; i++) {
                concurrentHashMap.put(i,i);
            }
            countDownLatch.countDown();
        }).start();

        new Thread(()->{
            for (int i = 10001; i <= 20000; i++) {
                concurrentHashMap.put(i,i);
            }
            countDownLatch.countDown();
        }).start();

        countDownLatch.await();
        Set<Map.Entry<Integer, Integer>> entries = concurrentHashMap.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            System.out.println(entry.getKey() + "---" + entry.getValue());
            count++;
            //Thread.sleep(1);
        }
        reloadByBufferedWriter(concurrentHashMap,new File("homework//demo.txt"));
        System.out.println(count);
        for (int i = 0; i <= 20001; i++) {
            if (!concurrentHashMap.contains(i))
                System.out.println("error is no" + i);
        }

    }



    public static void reloadByBufferedWriter(ConcurrentHashMap<Integer, Integer> concurrentHashMap, File file) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            Set<Map.Entry<Integer, Integer>> entries = concurrentHashMap.entrySet();
            for (Map.Entry<Integer, Integer> entry : entries) {
                bw.write(entry.getKey()+"");
                bw.newLine();
                //Thread.sleep(1);
            }

            bw.close();
        } catch (IOException e) {
            System.out.println("路径错误");
        }
    }


}
